package common

import (
	"fmt"
	"gin-chat-server/models"
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func init() {

	config := LoadingConfig()
	if config == nil {
		panic("config is nil")
	}
	host := config.Database.Host
	port := config.Database.Port
	username := config.Database.UsrName
	password := config.Database.Password

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, config.Database.DBName)
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}

	log.Println("database connect success")
	// 自动迁移表结构
	DB.AutoMigrate(
		&models.User{},
		&models.Room{},
		&models.RoomMember{},
		&models.Message{},
		&models.MessageRead{},
		&models.Friend{},
		&models.FriendRequest{},
		&models.UserStatus{},
		&models.RoomInvite{},
	)
}

func GetDB() *gorm.DB {
	return DB
}
